<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <#include "/common/plateform/include/common-base.ftl" >
    <title>网关路由配置</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
          name="viewport">
</head>
<body class="hold-transition ${sysColor} sidebar-mini">
<div class="wrapper">

    <!-- top start -->
    <#include "/common/plateform/top.ftl" >
    <!-- top end -->
    <!-- left start -->
    <#include "/common/plateform/left-project.ftl" >
    <!-- left end-->

    <div class="content-wrapper">
        <!-- Main start -->
        <section class="content">
            <div class="row">
                <div class="col-xs-12">

                    <!------搜索  start ------->
                    <div class="box box-info" id="searchForm-box">
                        <!--搜索title  start -->
                        <div class="box-header with-border">
                            <h3 class="box-title"><i class="fa fa-search"></i> 网关路由配置</h3>
                            <div class="box-tools pull-right">
                                <button type="button" class="btn btn-box-tool"
                                        data-widget="collapse"><i class="fa fa-minus"></i>
                                </button>
                            </div>
                        </div>
                        <!--搜索title  end -->
                        <div class="box-body">

                            <form id="searchForm" class="form-horizontal" action="javascript:;">
                                <input type="hidden" name="pageName" value="sys-zuul-route">
                                <input type="hidden" name="formName" value="searchForm">
                                <input type="hidden" name="sysZuulRoute.w_sysName" value="">
                                <div class="form-group">
                                    <div class="col-sm-2 text-right"><label class="control-label">服务Id：</label>
                                    </div>
                                    <div class="col-sm-4">
                                        <input type="text" class="form-control clean" name="sysZuulRoute.wl_serviceId"
                                               value=""/>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-12 text-center">
                                        <button type="button" class="btn btn-success"
                                                onclick="getTableDatas();"><i
                                                class="fa fa-search"></i> 查询
                                        </button>&nbsp;
                                        <button type="button" class="btn btn-warning"
                                                onclick="mytools.cleanData('#searchForm');">重置
                                        </button>&nbsp;
                                        <button onclick="toAdds();" class="btn btn-primary"
                                                type="button"><i class="fa fa-plus-circle"></i> 增加
                                        </button>&nbsp;
                                        <button onclick="mytools.loadCacheZuulRoute();" class="btn btn-danger"
                                                type="button"><i class="fa fa-refresh"></i> 刷新缓存
                                        </button>
                                        <button onclick="setBlackWhite()" class="btn btn-info"
                                                type="button"><i class="fa fa-cog"></i> 黑白名单设置
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <!------- 搜索 end -------->

                    <!------- 列表 start -------->
                    <div class="box box-success">
                        <div class="box-body">
                            <!--data-show-refresh="false" data-show-columns="true" data-show-export="true" -->
                            <table id="table-list" class="table table-bordered table-hover my-table-list"
                                   data-toolbar="#table-toolbar" data-cache="false" data-resizable="false" data-unique-id="sysZuulRoute.infoId"
                                   data-sortable="true" data-sort-order="desc" data-sort-name="sysZuulRoute.service_id"
                                   data-pagination="true" data-page-list="[10,15,20,50]" data-page-number="1" data-page-size="10">
                                <thead>
                                <tr>
                                    <th data-formatter="mytools.funPageNumber" data-align="center">序号</th>
                                    <th data-field="sysZuulRoute.serviceName" >服务名称</th>
                                    <th data-field="sysZuulRoute.serviceId" data-sortable="true" >服务ID</th>
                                    <th data-field="sysZuulRoute.path">请求路径</th>
                                    <th data-field="sysZuulRoute.url" >url</th>
                                    <th data-field="sysZuulRoute.retryable" data-formatter="TOrFFormatter" >是否可重试</th>
                                    <th data-field="sysZuulRoute.enabled" data-formatter="yesOrNoFormatter">是否启用</th>
                                    <th data-field="sysZuulRoute.stripPrefix" data-formatter="TOrFFormatter">是否过滤前缀</th>
                                    <th data-formatter="tableOptFormatter">操作</th>
                                </tr>
                                </thead>
                            </table>




                        </div>
                    </div>
                    <!------- 列表 end -------->
                </div>
            </div>
        </section>
        <!-- Main end -->

        <div class="modal fade" id="my_modal" tabindex="-1" role="dialog"
             aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            &times;
                        </button>
                        <h4 class="modal-title">
                            <font color="red">信息添加/修改</font>&nbsp;
                        </h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal" role="form" id="submitForm" action="javascript:;">
                            <input type="hidden" name="pageName" value="sys-zuul-route"/>
                            <input type="hidden" name="formName" value="editForm"/>
                            <input type="hidden" name="sysZuulRoute.sysName"/>
                            <input type="hidden" id="w_infoId" class="clean"
                                   data-name="sysZuulRoute.infoId" name="sysZuulRoute.w_infoId" value=""/>
                            <input type="hidden" id="formToken" name="formToken"
                                   value="${formToken}"/>

                            <div class="box-body" id="submitFormData">
                                <div>
                                    <div class="tab-content">
                                        <div class="tab-pane active" id="tab_1">
                                            <div class="form-group">
                                                <label class="col-sm-3 control-label">服务名称：</label>
                                                <div class="col-sm-8">
                                                    <input type="text" id="serviceName"
                                                           data-name="sysZuulRoute.serviceName" name="sysZuulRoute.serviceName"
                                                           class="form-control clean"
                                                           placeholder="此项不能为空"
                                                           data-bv-notempty="true"
                                                           data-bv-notempty-message="此项不能为空"/>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-3 control-label">请求路径：</label>
                                                <div class="col-sm-8">
                                                    <input id="path" name="sysZuulRoute.path" onblur="checkIsExsit(this)"
                                                           data-name="sysZuulRoute.path"
                                                           class="form-control clean"
                                                           placeholder="必须和server.context-path配合，例如：/test/**"
                                                           data-bv-notempty="true"
                                                           data-bv-notempty-message="此项不能为空"/>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-3 control-label">选择路由类型：</label>
                                                <div class="col-sm-8 form-control-static" onchange="changeRouteType(this)">
                                                    <input type="radio" name="sysZuulRoute.routeType" id="routeType_serviceid"
                                                           value="serviceid" checked="checked"/>服务ID
                                                    <input type="radio" name="sysZuulRoute.routeType" id="routeType_url"
                                                           value="url"/>映射URL
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-3 control-label">服务Id：</label>
                                                <div class="col-sm-8">
                                                    <input id="serviceId" name="sysZuulRoute.serviceId"
                                                           data-name="sysZuulRoute.serviceId"
                                                           class="form-control clean"
                                                    />
                                                </div>
                                            </div>
                                            <div class="form-group" style="display: none">
                                                <label class="col-sm-3 control-label">映射URL：</label>
                                                <div class="col-sm-8">
                                                    <input id="url" name="sysZuulRoute.url"
                                                           data-name="sysZuulRoute.url"
                                                           class="form-control clean"
                                                    />
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-3 control-label">服务登录地址：</label>
                                                <div class="col-sm-8">
                                                    <input id="serviceId" name="sysZuulRoute.loginUrl"
                                                           data-name="sysZuulRoute.loginUrl"
                                                           class="form-control clean"/>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-3 control-label">流量限制：</label>
                                                <div class="col-sm-8">
                                                    <input name="sysZuulRoute.rateLimit" data-name="sysZuulRoute.rateLimit"
                                                           class="form-control clean" value="1000" maxlength="4"/>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-3 control-label">是否可重试：</label>
                                                <div class="col-sm-8 form-control-static">
                                                    <input type="radio" name="sysZuulRoute.retryable" id="retryable_true"
                                                           value="true" checked="checked"/>是
                                                    <input type="radio" name="sysZuulRoute.retryable" id="retryable_false"
                                                           value="false"/>否
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-3 control-label">是否过滤前缀：</label>
                                                <div class="col-sm-8 form-control-static">
                                                    <input type="radio" name="sysZuulRoute.stripPrefix" id="stripPrefix_true"
                                                           value="true"/>是
                                                    <input type="radio" name="sysZuulRoute.stripPrefix" id="stripPrefix_false"
                                                           value="false" checked="checked"/>否
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-3 control-label">是否启用：</label>
                                                <div class="col-sm-8 form-control-static">
                                                    <input type="radio" name="sysZuulRoute.enabled" id="enabled_1"
                                                           value="1" checked="checked"/>是
                                                    <input type="radio" name="sysZuulRoute.enabled" id="enabled_0"
                                                           value="0"/>否
                                                </div>
                                            </div>

                                        <div class="form-group">
                                            <label class="col-sm-3 control-label">是否开启日志：</label>
                                            <div class="col-sm-8">
                                                <input type="radio" name="sysZuulRoute.ifLog" id="ifLog_1" value="1" checked="checked"/>是
                                                <input type="radio" name="sysZuulRoute.ifLog" id="ifLog_0" value="0"/>否
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-sm-3 control-label">熔断配置：</label>
                                            <div class="col-sm-8">
                                                <input type="radio" name="sysZuulRoute.ifHystrix" onclick="showHystrix('1')" id="ifHystrix_1" value="1"/>开启
                                                <input type="radio" name="sysZuulRoute.ifHystrix" onclick="showHystrix('0')" id="ifHystrix_0" value="0" checked="checked"/>关闭
                                            </div>
                                        </div>
                                        <div class="form-group" id="hystrix-content" style="display: none;">
                                            <label class="col-sm-3 control-label">熔断条件：</label>
                                            <div class="col-sm-8">
                                                <input id="in-hystrix-content" name="sysZuulRoute.hystrixContent" data-name="sysZuulRoute.hystrixContent"
                                                       class="form-control clean"  maxlength="4"/>
                                            </div>
                                        </div>
                                    </div>
                                        <!-- /.tab-pane -->
                                    </div>
                                    <!-- /.tab-content -->
                                </div>
                                <!-- nav-tabs-custom -->
                            </div>
                            <div class="box-footer">
                                <button type="button" class="btn btn-success pull-left"
                                        onclick="mytools.closeModal('my_modal');">取消
                                </button>
                                <button type="button" class="btn btn-danger pull-right"
                                        onclick="saveItem('submitForm');">提 交
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <!-- /.modal-content -->
            </div>
        </div>

        <script>
            var clickMenu = "zuul-route-list";
            myPage = 10;
            var $table=$('#table-list'),tableTotalRows=0;
            var defSysEname = strUtil.doNull(strUtil.getLocalStorage("sysEname"), ""),defSysCname=strUtil.doNull(strUtil.getLocalStorage("sysCname"), "");
            $(function () {
                $("#searchForm").find("input[name='sysZuulRoute.w_sysName']").val(defSysEname);
                //1、加载分页列表数据
                // getTableDatas();
                //调用公用方法初始化bootstrapTable表单配置
                mytools.initBootstrapTable({
                    url:common_list_url,
                    searcBoxId:"#searchForm-box",
                    exportFileName:"网关路由管理"
                });
                var allTableData = $table.bootstrapTable('getData');
                tableTotalRows=allTableData.length;
                console.log('allTableData',allTableData,tableTotalRows);
            });
            //给模态窗口内form表单内的所有支持必填项的元素注入校验
            $(".modal").on('shown.bs.modal', function () {
                $(this).find("form").each(function () {
                    var formId = $(this).attr("id");
                    if (!strUtil.isNull(formId)) {
                        formId = "#" + formId;
                        setValidate(formId);//定义add表单验证属性
                        mytools.cleanValidate(formId);//清空上次校验规则提示
                    }
                });
            });

            //读取（查询、编辑）数据
            function toLoad(id, type) {
                var paramLoadData = {};
                paramLoadData['pageName']="sys-zuul-route";
                paramLoadData['formName']="searchForm";

                paramLoadData['sysZuulRoute.w_infoId']=id;
                $.ajax({
                    type: 'get', url: common_info_url, dataType: 'json',
                    data: paramLoadData,
                    success: function (myData) {
                        //console.log(myData);
                        showData(type, myData);
                    }
                });
            }

            function del(infoId){
                layer.confirm('您确认要删除此服务吗？', { btn: ['确认','取消'] },
                    function(){
                        $.ajax({type:'post', url:common_submit_url, dataType:'json',
                            data:{'pageName':'sys-zuul-route','formName':'delForm','sysZuulRoute.w_infoId':infoId},
                            success: function(myData){
                                console.log("sysZuulRoute",myData);
                                if(myData.flag=='T'){
                                    layer.alert('删除操作成功！');
                                    getTableDatas();
                                    // loadCache();
                                }else{
                                    layer.alert('操作失败！'+myData.msg);
                                }
                            }
                        });
                    },
                    function(){}
                );
            }

            function checkIsExsit(obj) {
                if(strUtil.isNull($(obj).val())){
                    return;
                }
                var thisObjInfoId =$("#submitForm").find("input[name='sysZuulRoute.w_infoId']").val();
                var index_load = layer.load(1, {shade: false});
                var paramLoadData = {};
                paramLoadData['pageName']='sys-zuul-route';
                paramLoadData['formName']='searchForm';
                paramLoadData['sysZuulRoute.w_path']=$(obj).val();
                var inputId = $(obj).attr('id');
                $.getJSON(common_list_url,paramLoadData, function(myData2){
                    console.log('sysZuulRoute.valid.res',myData2);
                    layer.close(index_load);
                    if(myData2.total>0){
                        var oldInfoId = myData2.rows[0]["sysZuulRoute"].infoId;
                        if(strUtil.isNull(thisObjInfoId) || thisObjInfoId!=oldInfoId){
                            layer.tips('该过滤路径已存在，请更换其他', '#'+inputId, {tips: 3});
                            $(obj).val('');
                            return;
                        }
                    }
                });
            }

            function toCache(infoId) {
                // var cachekey = "interfaceRegister_" + beanId;
                $.ajax({
                    type: 'get',
                    url: common_cache_url+"view",
                    data:{"cacheSpaceName":'zuul.routes',"cachekey":infoId},
                    dataType: 'json',
                    success: function (myData) {
                        console.log(myData);
                        if (myData.flag == "T") {
                            layer.open({
                                title: '查看缓存信息',
                                type: 1,
                                skin: 'layui-layer-demo', //样式类名
                                anim: 2,
                                shadeClose: true, //开启遮罩关闭
                                area: ['500px', '300px'],
                                content: "<div style='word-break:break-all;word-wrap:break-word;width:100%;padding:5px;'>" + myData.msg +"</div>"
                            });
                        } else {
                            layer.alert(myData.msg);
                        }
                    }
                });
            }

            function toAdds() {
                mytools.cleanData('#submitForm');
                $("#my_modal").modal("show");
                $("#submitForm").find("input[name='formName']").val("addForm");
                $("#submitForm").find("input[name='sysZuulRoute.sysName']").val(defSysEname);
                $("#submitForm").find("input[name='sysZuulRoute.serviceName']").val(defSysCname+"服务");
                if(tableTotalRows==0){
                    $("#submitForm").find("input[name='sysZuulRoute.path']").val('/'+defSysEname+'/**');
                }
                $("#submitForm").find("input[name='sysZuulRoute.loginUrl']").val('/'+defSysEname+'/login.jsp');
                $("#submitForm").find("input[name='sysZuulRoute.serviceId']").val(defSysEname.toUpperCase()+'-SERVER');

                initRadio("sysZuulRoute.retryable", "true");
                initRadio("sysZuulRoute.enabled", "1");
                initRadio("sysZuulRoute.stripPrefix", "false");
                initRadio("sysZuulRoute.routeType", "serviceid");
                $("#url").parent().parent().hide();
                $("#serviceId").parent().parent().show();
            }

            //反显数据
            function showData(type, myData) {
                console.log(myData);
                FormUtil.loadView("sysZuulRoute", myData["sysZuulRoute"]);
                if ("view" == type) {
                    $("#my_modal_view").modal("show");
                } else if ("edit" == type) {
                    $("#submitForm").find("input[name='formName']").val("editForm");
                    initRadio("sysZuulRoute.retryable", myData["sysZuulRoute"].retryable);
                    initRadio("sysZuulRoute.stripPrefix", myData["sysZuulRoute"].stripPrefix);
                    initRadio("sysZuulRoute.enabled", myData["sysZuulRoute"].enabled);
                    var routeType = myData["sysZuulRoute"].routeType;
                    initRadio("sysZuulRoute.routeType", myData["sysZuulRoute"].routeType);
                    if("url"==routeType){
                        $("#url").parent().parent().show();
                        $("#serviceId").parent().parent().hide();
                    }else {
                        $("#url").parent().parent().hide();
                        $("#serviceId").parent().parent().show();
                    }
                    $("#my_modal").modal("show");

                    // initSelect("callType", myData["tInterfaceRegister"].callType);
                }
            }

            function saveItem(formId) {
                var validate = $('#' + formId).data('bootstrapValidator').validate();
                if (!validate.isValid()) { //如果校验不通过就返回
                    return;
                }
                var index_submit = layer.confirm('确认提交操作吗？', {
                        btn: ['确认', '取消'],
                        closeBtn: 0,
                        offset: '220px'
                    }
                    , function () {
                        layer.close(index_submit);
                        $.ajax({
                            type: 'post', url: common_submit_url, dataType: 'json',
                            data: $("#" + formId).serialize(),
                            success: function (myData) {
                                console.log(myData);
                                //layer.alert(myData.msg, {icon: 1,closeBtn: 0,offset: '220px'});
                                if (myData.flag == 'T') {
                                    getTableDatas();
                                    mytools.loadCacheZuulRoute();
                                    //layer.alert("操作成功", {icon: 1, closeBtn: 0, offset: '220px'});
                                } else {
                                    layer.alert(myData.msg, {
                                        icon: 1,
                                        closeBtn: 0,
                                        offset: '220px'
                                    });
                                }
                                mytools.closeModal("my_modal");
                            }
                        });
                    });
            }

            /**
            function loadCache() {
                $.ajax({
                    type: 'post',
                    url: "${ctx}/protocol/cache.action",
                    dataType: 'json',
                    success: function (myData) {
                        layer.alert(myData.msg, {icon: 1, closeBtn: 0, offset: '220px'});
                        getTableDatas();
                    }
                });
            }**/

            function getTableDatas() {
                $table.bootstrapTable("refresh");
            }

            function initRadio(elemname, selVl) {
                var myobj = document.getElementsByName(elemname);
                if (myobj == null) return;
                for (var i = 0; i < myobj.length; i++) {
                    if (myobj[i].value == selVl) {
                        myobj[i].checked = "true";
                    }
                }
            }

            function initSelect(elemid, selVl) {
                var myobj = document.getElementById(elemid);
                if (myobj == null) return;
                for (var i = 0; i < myobj.options.length; i++) {
                    if (myobj.options[i].value == selVl) {
                        myobj.selectedIndex = i;
                    }
                }
            }

            //1.定义校验规则-定义
            function setValidate(id) {
                $(id).each(function () {
                    $(this).bootstrapValidator({
                        feedbackIcons: {
                            valid: 'glyphicon glyphicon-ok',
                            invalid: 'glyphicon glyphicon-remove',
                            validating: 'glyphicon glyphicon-refresh'
                        }, /** 以下需要结合实际业务清空补充个表单元素的验证规则 **/
                        fields: {
                            /** 可自定义新增验证规则   **/
                             "sysZuulRoute.rateLimit":{
								validators: {
								regexp: {
								regexp: /^[0-9]+$/,
								message: '只能是数字'
								}
								}
								},
                            "sysZuulRoute.hystrixContent":{
                                validators: {
                                    regexp: {
                                        regexp: /^[0-9]+$/,
                                        message: '只能是数字'
                                    }
                                }
                            }
                        }
                    });
                });
            }


            function serverStatusFormatter(value) {
                if(value=='0'){
                    return "<font class='red'><i class='fa fa-stop-circle'></i> 已停用</font>";
                }else{
                    return "<font class='blue'><i class='fa fa-area-chart'></i> 已启用</font>";
                }
            }
            function yesOrNoFormatter(value) {
                if(value=='1'){
                    return "<span class='blue'>是</span>";
                }else{
                    return "否";
                }
            }
            function TOrFFormatter(value) {
                if(value=='true'){
                    return "是";
                }else{
                    return "否";
                }
            }

            function changeRouteType(obj) {
                var redioObj = $(obj).find("input[name='sysZuulRoute.routeType']:checked");
                var value = redioObj.val();
                if("url"==value){
                    $("#url").parent().parent().show();
                    $("#serviceId").parent().parent().hide()
                    $("#serviceId").val("");
                }else{
                    $("#serviceId").parent().parent().show();
                    $("#url").parent().parent().hide()
                    $("#url").val("");
                }
                // console.log();
            }
            function tableOptFormatter(value, row, index) {
                var obj = row.sysZuulRoute;
                var infoId = obj.infoId;
                var enabled = obj.enabled;
                var htmls ="";
                htmls += "<button type=\"button\" class=\"btn btn-warning btn-xs\" onclick=\"toLoad('"+infoId+"','edit');\">修改</button>&nbsp;";
                if(enabled=='0'){
                    htmls += "<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"del('"+infoId+"');\">删除</button>&nbsp;";
                }
                htmls += "<button type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"toCache('"+infoId+"');\">查看缓存</button>";
                return htmls;
            }

            function setBlackWhite(){
                var purl = "${ctx}/sendPage/plateform/admin/project/black-white-list";
                mytools.pjax(purl);
            }
            function showHystrix(type) {
                if(type=="1"){
                    $("#hystrix-content").show();
                } else {
                    $("#hystrix-content").hide();
                    $("#in-hystrix-content").val("");
                }
            }
        </script>


    </div>
    <!-- /.content-wrapper -->
    <!-- foot start -->
    <#include "/common/plateform/foot.ftl">
    <!-- foot start -->

</div>
</body>


</html>
